package org.gp.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.gp.core.entity.Activity;
import org.gp.core.entity.ActivityUserRelation;
import org.gp.core.entity.User;
import org.gp.core.entity.WxUserInfo;
import org.gp.core.entity.dto.ResponseDTO;
import org.gp.core.entity.enums.DTOCodeEnum;
import org.gp.core.entity.result.UserInfoResult;
import org.gp.core.exception.BusinessException;
import org.gp.core.mapper.ActivityMapper;
import org.gp.core.mapper.ActivityUserRelationMapper;
import org.gp.core.mapper.UserMapper;
import org.gp.core.service.IUserService;
import org.gp.core.service.TokenManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户表  服务实现类
 * </p>
 *
 * @author LuoLiang
 * @since 2017-01-24
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ActivityUserRelationMapper activityUserRelationMapper;
    @Resource
    private TokenManager tokenManager;
    @Value("${be.username}")
    private String username;
    @Value("${be.password}")
    private String password;

    /**
     * 根据微信返回的用户信息生成数据库用户数据
     *
     * @param wxUserInfo
     */
    @Override
    public User wxInitUserByWx(WxUserInfo wxUserInfo) {
        User user = new User();
        user.setCity(wxUserInfo.getCity());
        user.setCountry(wxUserInfo.getCountry());
        user.setProvince(wxUserInfo.getProvince());
        user.setNickname(wxUserInfo.getNickName());
        user.setSex(Integer.parseInt(wxUserInfo.getSex()));
        user.setHeadimgurl(wxUserInfo.getHeadImgUrl());
        user.setOpenid(wxUserInfo.getOpenId());

        boolean res = insert(user);
        if (!res) {
            log.error("插入用户数据失败:{}", JSON.toJSONString(user));
        } else {
            log.info("生成用户信息成功：{}", JSON.toJSONString(user));
        }

        return user;
    }

    /**
     * 根据id查询用户信息
     * 个人信息功能
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseDTO<UserInfoResult> wxGetUserInfo(Integer userId) {
        UserInfoResult userInfoResult = new UserInfoResult();
        ResponseDTO<UserInfoResult> res = new ResponseDTO<>();

        try {
            User user = selectById(userId);

            userInfoResult.setNickName(user.getNickname());
            userInfoResult.setSex(user.getSex() == 1 ? "男" : "女");//设置性别
            userInfoResult.setCity(user.getCity());
            userInfoResult.setProvince(user.getProvince());
            userInfoResult.setCountry(user.getCountry());
            userInfoResult.setHeadImgUrl(user.getHeadimgurl());

            EntityWrapper<Activity> activityEntityWrapper = new EntityWrapper<>();//实例化条件查询
            activityEntityWrapper.where("SPONSOR_USERID={0}", userId);//查询发起人为当前传入用户的活动

            userInfoResult.setActivityNum(activityMapper.selectCount(activityEntityWrapper));

            activityEntityWrapper = new EntityWrapper<>();
            activityEntityWrapper.where("ispass={0}", "1");
            activityEntityWrapper.and("SPONSOR_USERID={0}", userId);
            userInfoResult.setNotPassActivityNum(activityMapper.selectCount(activityEntityWrapper));//查询当前传入用户发起的未通过审核的活动数量

            EntityWrapper<ActivityUserRelation> relationEntityWrapper = new EntityWrapper<>();
            relationEntityWrapper.where("user_id={0}", userId);//查询当前传入用户所参加的活动

            userInfoResult.setJoinActivityNum(activityUserRelationMapper.selectCount(relationEntityWrapper));

            res.setData(userInfoResult);
            res.setCode(DTOCodeEnum.SUCCESS.getDesc());
            log.debug("返回用户信息：{}", JSON.toJSONString(res));
        } catch (BusinessException e) {
            res.setCode(DTOCodeEnum.FAIL.getDesc());
            res.setResMsg("查询数据失败");
            log.error("查询数据失败：", e);
        }

        return res;
    }


    /**
     * 后台管理员登录
     *
     * @param name
     * @param pwd
     * @return
     */
    @Override
    public ResponseDTO adminLogin(String name, String pwd) {
        ResponseDTO dto = new ResponseDTO();

        if (username.equals(name) && password.equals(pwd)) {
            String token = tokenManager.createToken("admin");
            dto.setResMsg(token);
            dto.setCode(DTOCodeEnum.SUCCESS.getDesc());
        } else {
            dto.setCode(DTOCodeEnum.FAIL.getDesc());
            dto.setResMsg("账号或密码错误");
        }

        return dto;
    }

    @Override
    public ResponseDTO<List<User>> getUserList(Integer currentPage, Integer pageSize, String searchCondition) {
        ResponseDTO<List<User>> dto = new ResponseDTO<>();

        //分页参数构造
        Page<User> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(currentPage);

        try {
            List<User> userList = userMapper.selectUserListNotBlack(page, searchCondition);  //查询非黑名单用户列表
            userList.stream().forEach(user -> user.setAge(user.getSex() == 1 ? "男" : "女"));

            dto.setData(userList);
            dto.setCode(DTOCodeEnum.SUCCESS.getDesc());
            dto.setResMsg(page.getTotal() + "_" + page.getCurrent());
        } catch (Exception e) {
            dto.setCode(DTOCodeEnum.FAIL.getDesc());
            log.error("获取用户列表业务失败：", e);
        }

        return dto;
    }
}
